package com.example.smartwaterapi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.smartwaterapi.common.api.RestApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

import com.example.smartwaterapi.entity.WaterRecord;
import com.example.smartwaterapi.service.WaterRecordService;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 系统测试控制器
 * 用于API状态检查和性能测试
 */
@Slf4j
@RestController
@RequestMapping("/api/system/test")
@Tag(name = "系统测试接口", description = "包含API状态检查和性能测试等接口")
public class SystemTestController {
    
    @Autowired(required = false)
    @Qualifier("threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    
    // For testing scenarios
    @Autowired(required = false)
    @Qualifier("testThreadPoolTaskExecutor")
    private ThreadPoolTaskExecutor testThreadPoolTaskExecutor;
    
    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private WaterRecordService waterRecordService;

    /**
     * 检查API状态
     * @return API状态信息
     */
    @GetMapping("/api-status")
    @Operation(summary = "API状态检查", description = "用于前端检查API服务是否正常运行")
    @SentinelResource("apiStatus")
    public RestApiResponse<Map<String, Object>> checkApiStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("status", "online");
        status.put("serverTime", new Date().toString());
        status.put("version", "1.0.0");
        
        // 记录API状态检查
        log.info("API状态检查 - 状态正常");
        
        return RestApiResponse.ok("API状态正常", status);
    }
    
    /**
     * 线程池状态检查
     * @return 线程池状态信息
     */
    @GetMapping("/thread-pool")
    @Operation(summary = "线程池状态", description = "检查系统线程池的当前状态")
    @SentinelResource("threadPoolStatus")
    public RestApiResponse<Map<String, Object>> threadPoolStatus() {
        ThreadPoolTaskExecutor activeExecutor = threadPoolTaskExecutor != null ? 
                                               threadPoolTaskExecutor : 
                                               testThreadPoolTaskExecutor;
        
        if (activeExecutor == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "No thread pool executor available");
            return RestApiResponse.error("线程池未配置");
        }
        
        ThreadPoolExecutor threadPoolExecutor = activeExecutor.getThreadPoolExecutor();
        
        Map<String, Object> status = new HashMap<>();
        status.put("activeCount", threadPoolExecutor.getActiveCount());
        status.put("corePoolSize", threadPoolExecutor.getCorePoolSize());
        status.put("maxPoolSize", threadPoolExecutor.getMaximumPoolSize());
        status.put("poolSize", threadPoolExecutor.getPoolSize());
        status.put("queueSize", threadPoolExecutor.getQueue().size());
        status.put("taskCount", threadPoolExecutor.getTaskCount());
        status.put("completedTaskCount", threadPoolExecutor.getCompletedTaskCount());
        
        return RestApiResponse.ok("线程池状态", status);
    }
    
    /**
     * Redis连接测试
     * @return Redis连接状态
     */
    @GetMapping("/redis-status")
    @Operation(summary = "Redis状态检查", description = "检查Redis连接状态")
    @SentinelResource("redisStatus")
    public RestApiResponse<Map<String, Object>> redisStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            if (redisTemplate != null) {
                String testKey = "api_test_" + System.currentTimeMillis();
                redisTemplate.opsForValue().set(testKey, "test");
                Object value = redisTemplate.opsForValue().get(testKey);
                redisTemplate.delete(testKey);
                
                status.put("status", "connected");
                status.put("testValue", value);
                return RestApiResponse.ok("Redis连接正常", status);
            } else {
                status.put("status", "not_configured");
                return RestApiResponse.error("Redis未配置");
            }
        } catch (Exception e) {
            status.put("status", "error");
            status.put("message", e.getMessage());
            log.error("Redis连接测试失败", e);
            return RestApiResponse.error("Redis连接测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 耗时操作测试
     * @param delayMs 延迟毫秒数
     * @return 操作结果
     */
    @GetMapping("/delay")
    @Operation(summary = "延迟响应测试", description = "模拟耗时操作，用于测试前端超时处理")
    @SentinelResource("apiDelay")
    public RestApiResponse<Map<String, Object>> testDelay(@RequestParam(defaultValue = "1000") int delayMs) {
        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("delayMs", delayMs);
        result.put("timestamp", System.currentTimeMillis());
        
        return RestApiResponse.ok("延迟响应完成", result);
    }

    /**
     * 测试统计功能
     */
    @Operation(summary = "测试统计功能", description = "测试饮水统计功能")
    @GetMapping("/water-stats")
    public RestApiResponse<Map<String, Object>> testWaterStats(
            @RequestParam(required = false, defaultValue = "1") Long userId) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取每日总量
        Integer dailyTotal = waterRecordService.getUserDailyTotal(userId, LocalDate.now());
        result.put("dailyTotal", dailyTotal != null ? dailyTotal : 0);
        
        // 获取总饮水量
        Long allTimeTotal = waterRecordService.getUserAllTimeTotal(userId);
        result.put("allTimeTotal", allTimeTotal != null ? allTimeTotal.longValue() : 0L);
        
        // 获取周统计数据
        LocalDate today = LocalDate.now();
        LocalDate startOfWeek = today.minusDays(today.getDayOfWeek().getValue() - 1);
        var weeklyStats = waterRecordService.getUserDailyTotalsByDateRange(userId, startOfWeek, today);
        result.put("weeklyStats", weeklyStats);
        
        // 计算周总量
        int weeklyTotal = 0;
        if (weeklyStats != null) {
            for (Map<String, Object> day : weeklyStats) {
                if (day.get("total") instanceof Number) {
                    // 安全转换为int，避免ClassCastException
                    weeklyTotal += ((Number) day.get("total")).intValue();
                }
            }
        }
        result.put("weeklyTotal", weeklyTotal);
        
        return RestApiResponse.ok(result);
    }
    
    /**
     * 测试生成样例数据
     */
    @Operation(summary = "生成样例数据", description = "生成样例饮水记录")
    @GetMapping("/generate-sample")
    public RestApiResponse<String> generateSample(
            @RequestParam(required = false, defaultValue = "1") Long userId,
            @RequestParam(required = false, defaultValue = "5") Integer days) {
        
        LocalDate today = LocalDate.now();
        int recordsGenerated = 0;
        
        for (int i = 0; i < days; i++) {
            LocalDate date = today.minusDays(i);
            
            // 生成1-5条每日记录
            int recordCount = 1 + (int)(Math.random() * 5);
            
            for (int j = 0; j < recordCount; j++) {
                WaterRecord record = new WaterRecord();
                record.setUserId(userId);
                record.setAmount(150 + (int)(Math.random() * 350)); // 150-500ml
                record.setDrinkType("water");
                
                // 随机时间 (8:00 - 22:00)
                int hour = 8 + (int)(Math.random() * 14);
                int minute = (int)(Math.random() * 60);
                LocalDateTime recordTime = date.atTime(hour, minute);
                record.setRecordTime(recordTime);
                record.setRecordDate(date);
                record.setHour(hour);
                
                // 保存记录
                waterRecordService.addRecord(record);
                recordsGenerated++;
            }
        }
        
        return RestApiResponse.ok("成功生成 " + recordsGenerated + " 条样例数据");
    }
} 